import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_video_course.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/2/8.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///我的学习进度
class MyStudyRecoderProgressPage extends StatefulWidget {
  final UserStudyCourseBean courseBean;
  final int trainId;

  const MyStudyRecoderProgressPage({Key key, this.trainId, this.courseBean})
      : super(key: key);

  @override
  _MyStudyRecoderProgressPageState createState() =>
      _MyStudyRecoderProgressPageState();
}

class _MyStudyRecoderProgressPageState
    extends State<MyStudyRecoderProgressPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero, () {
      _getMyStudyRecoderProgressList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("学习进度"),
      ),

      ///填充布局
      body: RefreshIndicator(
        onRefresh: () async {
          await _getMyStudyRecoderProgressList();
          ToastUtils.showToast("已刷新");
          return true;
        },
        child: buildMainWidget(),
      ),
    );
  }

  List<UserStudyCourseBean> _list;

  ///获取我的学习记录
  Future<bool> _getMyStudyRecoderProgressList() async {
    Map<String, dynamic> map = Map();
    map["courseId"] = widget.courseBean.videoCourseId;
    if (widget.trainId != null) {
      map["trainId"] = widget.trainId;
    }
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.videoStudyProgressListUrl,
      queryParameters: map,
    );
    if (responseInfo.success) {
      List list = responseInfo.data;
      _list = [];
      list.forEach((element) {
        UserStudyCourseBean beanVideoCategory =
            UserStudyCourseBean.fromMap(element);
        _list.add(beanVideoCategory);
      });
    }
    if (mounted) {
      setState(() {});
    }

    return true;
  }

  buildMainWidget() {
    if (_list == null || _list.length == 0) {
      return Center(
        child: NoDataWidget(
          text: "暂无学习记录",
          clickCallBack: () {
            _getMyStudyRecoderProgressList();
          },
        ),
      );
    }
    //一个列表 切记不要再使用 Scaffold
    //否则会拦截事件 失去滑动联动效果
    return ListView.builder(
      //去除内边距
      padding: EdgeInsets.all(0),
      //列表子Item个数
      itemCount: _list.length,
      //每个子Item的布局构建
      itemBuilder: (BuildContext context, int index) {
        return buildBodyWidget(index);
      },
    );
  }

  buildStartStr(UserStudyCourseBean beanVideoCourse) {
    String startStr =
        "本小节总时长 ${getCourseTime(beanVideoCourse.videoSecond ~/ 1000)}";
    return startStr;
  }

  buildEndStr(UserStudyCourseBean beanVideoCourse) {
    String endStr =
        "已学习总时长 ${getCourseTime(beanVideoCourse.studySecond ~/ 1000)}";
    return endStr;
  }

  buildBodyWidget(int index) {
    UserStudyCourseBean beanVideoCourse = _list[index];

    String startStr = buildStartStr(beanVideoCourse);
    String endStr = buildEndStr(beanVideoCourse);
    //课件类型 0 视频 1 PPT 2  视频代码连接
    int videoTypes = beanVideoCourse.videoTypes;
    Widget studyWidget;

    studyWidget = Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          startStr,
          style: TextStyle(
            color: Color(0xff666666),
            fontSize: 14,
          ),
        ),
        Text(
          endStr,
          style: TextStyle(
            color: Color(0xff666666),
            fontSize: 14,
          ),
        ),
        SizedBox(
          height: 8,
        )
      ],
    );

    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(12),
      margin: EdgeInsets.only(top: 3),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 4, right: 6),
            padding: EdgeInsets.only(left: 6, right: 6),
            height: 18,
            decoration: BoxDecoration(
                color: Colors.blueGrey[200],
                borderRadius: BorderRadius.all(Radius.circular(4))),
            child: Text(
              "${index + 1}",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontSize: 12),
            ),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  "${beanVideoCourse.videoName}",
                  style: TextStyle(
                    fontWeight: FontWeight.w500,
                    fontSize: 16,
                  ),
                ),
                SizedBox(
                  height: 4,
                ),
                Text(
                  "本小节学习完成 ${(beanVideoCourse.studySecond * 1.0 / beanVideoCourse.videoSecond * 100).toInt()}%",
                  style: TextStyle(
                    color: Color(0xff666666),
                    fontSize: 14,
                  ),
                ),
                studyWidget,
                Text(
                  "最近学习时间 ${beanVideoCourse.updateTime}",
                  style: TextStyle(
                    color: Color(0xff666666),
                    fontSize: 14,
                  ),
                ),
                SizedBox(
                  height: 4,
                ),
                Text(
                  "参与学习时间 ${beanVideoCourse.createTime}",
                  style: TextStyle(
                    color: Color(0xff666666),
                    fontSize: 14,
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  String getCourseTime(int seconds) {
    int day = seconds ~/ (60 * 60 * 24); //换成天
    int hour = (seconds - (60 * 60 * 24 * day)) ~/
        3600; //总秒数-换算成天的秒数=剩余的秒数    剩余的秒数换算为小时
    int minute = (seconds - 60 * 60 * 24 * day - 3600 * hour) ~/
        60; //总秒数-换算成天的秒数-换算成小时的秒数=剩余的秒数    剩余的秒数换算为分
    int second = seconds -
        60 * 60 * 24 * day -
        3600 * hour -
        60 * minute; //总秒数-换算成天的秒数-换算成小时的秒数-换算为分的秒数=剩余的秒数
    //System.out.println(day+"天"+hour+"时"+minute+"分"+second+"秒");
    String dayStr = "$day";
    if (day < 10) {
      dayStr = "0$day";
    }
    String hourStr = "$hour";
    if (hour < 10) {
      hourStr = "0$hour";
    }

    String minuteStr = "$minute";
    if (minute < 10) {
      minuteStr = "0$minute";
    }

    String secondStr = "$second";
    if (second < 10) {
      secondStr = "0$second";
    }
    if (day > 0) {
      return "$dayStr天$hourStr小时$minuteStr分钟$secondStr秒";
    } else {
      return "$hourStr小时$minuteStr分钟$secondStr秒";
    }
  }
}
